/**   
 * @Title: FileUtils.java 
 * @Package com.git.gather 
 * @Description: 文件相关工具类
 * @author fanqinghui100@126.com   
 * @date 2014年6月2日 下午8:19:46 
 * @version V1.0   
 */
package com.git.gather;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

/**
 * @author fanqinghui100@126.com
 */
public class FileUtils extends org.apache.commons.io.FileUtils {

	/** UTF-8 */
	public final static String UTF_8 = "UTF-8";
	/** GBK */
	public final static String GBK = "GBK";
	/** Unicode */
	public final static String UNICODE = "Unicode";

	/**
	 * 获取当前系统换行符
	 *
	 * @return 系统换行符
	 */
	public static String getSystemLineSeparator() {
		return System.getProperty("line.separator");
	}

	/**
	 * 返回路径下的所有文件列表
	 * 
	 * @param filepath
	 * @return File[]
	 */
	public static File[] getFileList(String filepath) {
		File d = null;
		File list[] = null;
		d = new File(filepath);
		if (d.exists()) {
			list = d.listFiles();
		}
		return list;
	}

	/**
	 * 用encoding格式读取并返回filePathAndName文件内容
	 * 
	 * @param filePathAndName
	 *            文件路径及名称例如：D:\\xxx.txt"
	 * @param encoding
	 *            编码格式
	 * @return String
	 */
	public static String readTxt(String filePathAndName, String encoding) throws IOException {
		encoding = encoding.trim();
		StringBuffer sb = new StringBuffer("");
		String st = "";
		BufferedReader br = null;
		try {
			FileInputStream fs = new FileInputStream(filePathAndName);
			InputStreamReader isr;
			if (encoding.equals("")) {
				isr = new InputStreamReader(fs);
			} else {
				isr = new InputStreamReader(fs, encoding);
			}
			br = new BufferedReader(isr);
			try {
				String data = "";
				while ((data = br.readLine()) != null) {
					sb.append(data);
				}
			} catch (Exception e) {
				sb.append(e.toString());
			}
			st = sb.toString();
			if (st != null && st.length() > 1)
				st = st.substring(0, st.length() - 1);
		} catch (IOException es) {
			st = "";
		} finally {
			if (br != null)
				br.close();
		}
		return st;
	}

	/**
	 * 创建名称为 folderPath的文件夹
	 * 
	 * @param folderPath
	 * @return String
	 */
	public static String createFolder(String folderPath) {
		String txt = folderPath;
		try {
			java.io.File myFilePath = new java.io.File(txt);
			txt = folderPath;
			if (!myFilePath.exists()) {
				myFilePath.mkdir();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return txt;
	}

	/**
	 * 创建filePathAndName文件，并且写入fileContent文件内容
	 * 
	 * @param filePathAndName
	 *            文件路径及名称例如：D:\\xxx.txt"
	 * @param fileContent
	 *            文件内容
	 * @return
	 */
	public static void createFile(String filePathAndName, String fileContent) {
		try {
			String filePath = filePathAndName;
			filePath = filePath.toString();
			File myFilePath = new File(filePath);
			if (!myFilePath.exists()) {
				myFilePath.createNewFile();
			}
			FileWriter resultFile = new FileWriter(myFilePath);
			PrintWriter myFile = new PrintWriter(resultFile);
			String strContent = fileContent;
			myFile.println(strContent);
			myFile.close();
			resultFile.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 创建filePathAndName文件，并且用encoding字符格式写入fileContent内容
	 * 
	 * @param filePathAndName
	 *            文件路径及名称
	 * @param fileContent
	 *            文件内容
	 * @param encoding
	 *            编码格式：例如：GBK 或 UTF-8
	 * @return
	 */
	public static void createFile(String filePathAndName, String fileContent, String encoding) {
		try {
			String filePath = filePathAndName;
			filePath = filePath.toString();
			File myFilePath = new File(filePath);
			if (!myFilePath.exists()) {
				myFilePath.createNewFile();
			}
			PrintWriter myFile = new PrintWriter(myFilePath, encoding);
			String strContent = fileContent;
			myFile.println(strContent);
			myFile.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 删除文件
	 * 
	 * @param filePathAndName
	 *            文件路径及名称
	 * @return Boolean
	 */
	public static boolean delFile(String filePathAndName) {
		boolean bea = false;
		try {
			String filePath = filePathAndName;
			File myDelFile = new File(filePath);
			if (myDelFile.exists()) {
				myDelFile.delete();
				bea = true;
			} else {
				bea = false;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return bea;
	}

	/**
	 * 删除文件夹
	 * 
	 * @param folderPath
	 *            文件路径
	 * @return
	 */
	public static void delFolder(String folderPath) {
		try {
			delAllFile(folderPath);
			String filePath = folderPath;
			filePath = filePath.toString();
			File myFilePath = new File(filePath);
			myFilePath.delete();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 删除所有文件
	 * 
	 * @param path
	 *            路径
	 * @return
	 */
	public static boolean delAllFile(String path) {
		boolean bea = false;
		File file = new File(path);
		if (!file.exists()) {
			return bea;
		}
		if (!file.isDirectory()) {
			return bea;
		}
		String[] tempList = file.list();
		File temp = null;
		for (int i = 0; i < tempList.length; i++) {
			if (path.endsWith(File.separator)) {
				temp = new File(path + tempList[i]);
			} else {
				temp = new File(path + File.separator + tempList[i]);
			}
			if (temp.isFile()) {
				temp.delete();
			}
			if (temp.isDirectory()) {
				delAllFile(path + "/" + tempList[i]);
				delFolder(path + "/" + tempList[i]);
				bea = true;
			}
		}
		return bea;
	}

	/**
	 * 文件复制
	 * 
	 * @param oldPathFile
	 * @param newPathFile
	 * @return void
	 * @throws IOException
	 */
	public static void copyFile(String oldPathFile, String newPathFile) throws IOException {
	/*	FileOutputStream fs = null;
		InputStream inStream = null;
		try {
			@SuppressWarnings("unused")
			int bytesum = 0;
			int byteread = 0;
			File oldfile = new File(oldPathFile);
			if (oldfile.exists()) {
				inStream = new FileInputStream(oldPathFile);
				fs = new FileOutputStream(newPathFile);
				byte[] buffer = new byte[1024];
				while ((byteread = inStream.read(buffer)) != -1) {
					bytesum += byteread;
					fs.write(buffer, 0, byteread);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (inStream != null)
				inStream.close();
			if (fs != null)
				fs.close();
		}*/
        //NIO实现方式
        FileInputStream inputStream=new FileInputStream(new File(oldPathFile));
        FileOutputStream outputStream=new FileOutputStream(new File(newPathFile));
        FileChannel inputChannel=inputStream.getChannel();
        FileChannel outputChannel=outputStream.getChannel();
        ByteBuffer byteBuffer=ByteBuffer.allocate(1024);//直接allocate 从对内存中分配
        //or 下面 一种创建形式：既有数组中创建
      //  Byte[] bytes=new Byte[1024];
      //  byteBuffer=ByteBuffer.wrap(bytes);
        int i=0;
        while(true){
            i=inputChannel.write(byteBuffer);
         //   System.out.println(byteBuffer.position());//位置--开始位置
           // System.out.println(byteBuffer.capacity());//容量--这里指1024
            //System.out.println(byteBuffer.limit());//可读的总量
            if(i==-1){
                break;
            }
            byteBuffer.flip();//重置position开始位置
            outputChannel.write(byteBuffer);
        }
        inputChannel.close();
        outputChannel.close();
	}

	/**
	 * 文件夹复制
	 * @param oldPath
	 * @param newPath
	 * @return
	 */
	public static void copyFolder(String oldPath, String newPath) {
		try {
			new File(newPath).mkdirs();
			File a = new File(oldPath);
			String[] file = a.list();
			File temp = null;
			for (int i = 0; i < file.length; i++) {
				if (oldPath.endsWith(File.separator)) {
					temp = new File(oldPath + file[i]);
				} else {
					temp = new File(oldPath + File.separator + file[i]);
				}
				if (temp.isFile()) {
					FileInputStream input = new FileInputStream(temp);
					FileOutputStream output = new FileOutputStream(newPath + "/" + (temp.getName()).toString());
					byte[] b = new byte[1024 * 5];
					int len;
					while ((len = input.read(b)) != -1) {
						output.write(b, 0, len);
					}
					output.flush();
					output.close();
					input.close();
				}
				if (temp.isDirectory()) {
					copyFolder(oldPath + "/" + file[i], newPath + "/" + file[i]);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 文件移动
	 * @param oldPath
	 * @param newPath
	 * @return void
	 * @throws IOException
	 */
	public static void moveFile(String oldPath, String newPath) throws IOException {
		copyFile(oldPath, newPath);
		delFile(oldPath);
	}

	/**
	 * 文件夹移动
	 * @param oldPath
	 * @param newPath
	 * @return
	 */
	public static void moveFolder(String oldPath, String newPath) {
		copyFolder(oldPath, newPath);
		delFolder(oldPath);
	}

	/**
	 * 重命名文件或文件夹
	 * @param resFilePath 源文件路径
	 * @param newFileName  重命名
	 * @return 操作成功标识
	 */
	public static boolean renameFile(String resFilePath, String newFileName) {
		String newFilePath = formatPath(getParentPath(resFilePath) + "/" + newFileName);
		File resFile = new File(resFilePath);
		File newFile = new File(newFilePath);
		return resFile.renameTo(newFile);
	}

	/**
	 * 读取文件或者目录的大小
	 * @param distFilePath 目标文件或者文件夹
	 * @return 文件或者目录的大小，如果获取失败，则返回-1
	 */
	public static long genFileSize(String distFilePath) {
		File distFile = new File(distFilePath);
		if (distFile.isFile()) {
			return distFile.length();
		} else if (distFile.isDirectory()) {
			return FileUtils.sizeOfDirectory(distFile);
		}
		return -1L;
	}

	/**
	 * 判断一个文件是否存在
	 * @param filePath 文件路径
	 * @return 存在返回true，否则返回false
	 */
	public static boolean isExist(String filePath) {
		return new File(filePath).exists();
	}

	/**
	 * 为fileDir目录下fileName文件，返回写入管道对象（BufferedWriter）
	 * @param fileDir
	 * @param fileName
	 * @return BufferedWriter
	 */
	public static BufferedWriter getWriter(String fileDir, String fileName) {
		try {
			File f1 = new File(fileDir);
			if (!f1.exists()) {
				f1.mkdirs();
			}
			f1 = new File(fileDir, fileName);
			if (!f1.exists()) {
				f1.createNewFile();
			}
			BufferedWriter bw = new BufferedWriter(new FileWriter(f1.getPath(), true));
			return bw;
		} catch (Exception e) {
			System.out.println(e.getLocalizedMessage());
			return null;
		}
	}

	/**
	 * 用encoding字符格式读取fileDir目录下fileName文件，返回读取文件管道对象（BufferedReader）
	 * 
	 * @param fileDir
	 * @param fileName
	 * @param encoding
	 * @return
	 */
	public static BufferedReader getReader(String fileDir, String fileName, String encoding) {
		try {
			File file = new File(fileDir, fileName);
			InputStreamReader read = new InputStreamReader(new FileInputStream(file), encoding);
			BufferedReader br = new BufferedReader(read);
			return br;
		} catch (FileNotFoundException ex) {
			ex.printStackTrace();
			return null;
		} catch (IOException e) {
			e.printStackTrace();
			return null;
		}
	}

	/**
	 * 获取文件父路径
	 *
	 * @param path
	 *            文件路径
	 * @return 文件父路径
	 */
	public static String getParentPath(String path) {
		return new File(path).getParent();
	}

	/**
	 * 获取相对路径
	 * @param fullPath   全路径
	 * @param rootPath   根路径
	 * @return 相对根路径的相对路径
	 */
	public static String getRelativeRootPath(String fullPath, String rootPath) {
		String relativeRootPath = null;
		String _fullPath = formatPath(fullPath);
		String _rootPath = formatPath(rootPath);

		if (_fullPath.startsWith(_rootPath)) {
			relativeRootPath = fullPath.substring(_rootPath.length());
		} else {
			throw new RuntimeException("要处理的两个字符串没有包含关系，处理失败！");
		}
		if (relativeRootPath == null)
			return null;
		else
			return formatPath(relativeRootPath);
	}

	/**
	 * 格式化文件路径，将其中不规范的分隔转换为标准的分隔符,并且去掉末尾的"/"符号。
	 * @return 格式化后的文件路径
	 */
	public static String formatPath(String path) {
		String reg0 = "////＋";
		String reg = "////＋|/＋";
		String temp = path.trim().replaceAll(reg0, "/");
		temp = temp.replaceAll(reg, "/");
		if (temp.endsWith("/")) {
			temp = temp.substring(0, temp.length() - 1);
		}
		if (System.getProperty("file.separator").equals("//")) {
			temp = temp.replace("/", "//");
		}
		return temp;
	}
	/**
	 * 输入流转换成字节数组
	 * @param in：输入流
	 * @return byte[] 字节
	 */
	public static byte[] readBytes(InputStream in) throws IOException {
		BufferedInputStream bufin = new BufferedInputStream(in);
		int buffSize = 1024;
		ByteArrayOutputStream out = new ByteArrayOutputStream(buffSize);
		System.out.println("按照文件大小为bytes:" + in.available());
		byte[] temp = new byte[buffSize];
		int size = 0;
		while ((size = bufin.read(temp)) != -1) {
			out.write(temp, 0, size);
		}
		bufin.close();
		byte[] content = out.toByteArray();
		return content;
	}
}
